<template>
  <div class="container">
    <navBar :title="'隐患登记'" :backStep="'index'"></navBar>
    <div class="formBox">
      <div class="formItem">
        <van-cell title="隐患名称:">
          <template #default>
            <input
              type="text"
              v-model="formInfo.jobName"
              class="inputCss"
              placeholder="请输入"
            />
          </template>
          <!-- <template #icon>
            <span style="color: red">* </span>
          </template> -->
        </van-cell>
      </div>

      <div class="formItem">
        <div class="cellCss">
          <div class="cellCssTitle">隐患描述:</div>
          <div>
            <textarea
              v-model="formInfo.jobContent"
              placeholder="请输入"
              placeholder-class="textarea-placeholder"
            />
          </div>
        </div>
      </div>

      <div class="formItem">
        <div class="cellCss">
          <div class="cellCssTitle">隐患图片:</div>
          <div>
            <van-uploader
              accept="image/jpeg,image/png"
              v-model="uploader1"
              :max-count="3"
              :after-read="afterRead"
              :before-delete="deleteSubmitPic"
              :before-read="beforeRead"
            />
          </div>
        </div>
        <van-cell title="检查时间:" is-link @click="showTimePicker = true">
          <template #default>
            {{ startTime }}
          </template>
        </van-cell>
        <van-cell title="检查人:" is-link @click="showPicker5 = true">
          <template #default>
            {{ checkPerson }}
          </template>
        </van-cell>
 
      </div>

      <div class="formItem">
        <van-cell title="隐患等级:" is-link @click="showPicker = true">
          <template #default>
            {{ problemGrade }}
          </template>
        </van-cell>
        <van-cell title="隐患来源:" is-link @click="showPicker1 = true">
          <template #default>
            {{ problemSource }}
          </template>
        </van-cell>
        <van-cell title="隐患类别:" is-link @click="showPicker2 = true">
          <template #default>
            {{ problemSort }}
          </template>
        </van-cell>
      </div>
      <div class="formItem">
        <van-cell title="治理类型:" is-link @click="showPicker3 = true">
          <template #default>
            {{ solveSort }}
          </template>
        </van-cell>
        <van-cell title="隐患治理期限:" v-if="solveSortValue == '2'">
          <template #default>
            <input
              type="text"
              v-model="solveTime"
              class="inputCss"
              placeholder="请输入"
            />
          </template>
          <template #right-icon>
            <span>天</span>
          </template>
        </van-cell>
        <van-cell title="整改负责人:" is-link @click="showPicker4 = true">
          <template #default>
            {{ solveRespondent }}
          </template>
        </van-cell>
      </div>

      <div class="formItem"></div>
    </div>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        title="隐患等级"
        show-toolbar
        :columns="options4"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <van-popup v-model="showPicker1" position="bottom">
      <van-picker
        title="隐患来源"
        show-toolbar
        :columns="columns1"
        @confirm="onConfirm1"
        @cancel="showPicker1 = false"
      />
    </van-popup>
    <van-popup v-model="showPicker2" position="bottom">
      <van-picker
        title="隐患类别"
        show-toolbar
        :columns="columns2"
        @confirm="onConfirm2"
        @cancel="showPicker2 = false"
      />
    </van-popup>
    <van-popup v-model="showPicker3" position="bottom">
      <van-picker
        title="治理类型"
        show-toolbar
        :columns="options6"
        @confirm="onConfirm3"
        @cancel="showPicker3 = false"
      />
    </van-popup>
    <van-popup v-model="showPicker4" position="bottom">
      <van-picker
        title="整改负责人"
        show-toolbar
        :columns="columns4"
        @confirm="onConfirm4"
        @cancel="showPicker4 = false"
      />
    </van-popup>
    <van-popup v-model="showPicker5" position="bottom">
      <van-picker
        title="整改负责人"
        show-toolbar
        :columns="columns5"
        @confirm="onConfirm5"
        @cancel="showPicker5 = false"
      />
    </van-popup>
    <van-popup v-model="showTimePicker" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择检查时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmDate"
        @cancel="cancelShowTimePicker"
      />
    </van-popup>
    <van-goods-action>
      <van-goods-action-button
        :style="{
          background: '#0077FF',
          color: '#fff',
        }"
        type="danger"
        text="提交登记"
        @click="onClickButton"
      />
    </van-goods-action>
  </div>
</template>

<script>
import navBar from '@/components/navBar.vue'
import { dictionaryListApi, addProblemApi, uploadApi } from '@/api/index'

import { userListApi } from '@/api/ticket'
export default {
  name: 'addProblem',
  props: {},
  components: {
    navBar,
  },
  data() {
    return {
      formInfo: {
        jobName: '',
        jobContent: '',
      },
      problemGrade: '请选择隐患等级',
      problemGradeValue: '',
      problemSource: '请选择隐患来源',
      problemSourceValue: '',
      problemSort: '请选择隐患类别',
      problemSortValue: '',
      solveSort: '请选择治理类型',
      solveSortValue: '',
      solveRespondent: '请选择整改负责人',
      solveRespondentValue: '',
      solveTime: '',
      showPicker: false,
      showPicker1: false,
      showPicker2: false,
      showPicker3: false,
      showPicker4: false,
      uploader1: [],
      columns1: [],
      columns2: [],
      columns4: [],
      options4: [],
      options6: [],
      columns5: [],
      uploaderSubmit: [],
      testMsg: '',
      showTimePicker: false,
      currentDate: new Date(),
      minDate: new Date(2024, 0, 1),
      maxDate: new Date(2029, 10, 1),
      startTime: '',
      checkPerson: '',
      checkPersonValue: '',
      showPicker5: false,
      checkLocation: '点击获取当前位置',
    }
  },
  created() {
    this.dictionaryList()
    const time = new Date()
    this.startTime = `${time.getFullYear()}-${(time.getMonth() + 1)
      .toString()
      .padStart(2, '0')}-${time.getDate().toString().padStart(2, '0')} ${time
      .getHours()
      .toString()
      .padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}:${time
      .getSeconds()
      .toString()
      .padStart(2, '0')}`

    let isLoginMsg = JSON.parse(sessionStorage.getItem('loginInfo'))
    // console.log(isLoginMsg)
    this.checkPerson =
      isLoginMsg.departmentName + '-' + isLoginMsg.name + '-' + isLoginMsg.phone
    this.checkPersonValue = isLoginMsg.userId
  },
  methods: {
    async dictionaryList() {
      const res = await dictionaryListApi({
        type: 'danger_grade',
      })
      this.options4 = res.data.map((item) => {
        return {
          text: item.name,
          value: item.code,
        }
      })
      const res2 = await dictionaryListApi({
        type: 'danger_source',
      })
      this.columns1 = res2.data.map((item) => {
        return {
          text: item.name,
          value: item.code,
        }
      })
      const res3 = await dictionaryListApi({
        type: 'danger_kind',
      })
      this.columns2 = res3.data.map((item) => {
        return {
          text: item.name,
          value: item.code,
        }
      })
      const res4 = await dictionaryListApi({
        type: 'govern_kind',
      })
      this.options6 = res4.data.map((item) => {
        return {
          text: item.name,
          value: item.code,
        }
      })
      const res5 = await userListApi({ name: null })

      this.columns4 = res5.data.map((item) => {
        return {
          text: item.departmentName + '-' + item.name + '-' + item.phone,
          value: item.id,
        }
      })
      this.columns5 = res5.data.map((item) => {
        return {
          text: item.departmentName + '-' + item.name + '-' + item.phone,
          value: item.id,
        }
      })
    },
    async onClickButton() {
      if (
        !this.formInfo.jobName ||
        !this.formInfo.jobContent ||
        !this.problemGradeValue ||
        !this.problemSourceValue ||
        !this.problemSortValue ||
        !this.solveSortValue
      ) {
        this.$toast.fail('请填写完整信息')
        return
      }
      const res = await addProblemApi({
        dangerName: this.formInfo.jobName,
        dangerDescribe: this.formInfo.jobContent,
        dangerImg1: this.uploaderSubmit[0] ? this.uploaderSubmit[0] : '',
        dangerImg2: this.uploaderSubmit[1] ? this.uploaderSubmit[1] : '',
        dangerImg3: this.uploaderSubmit[2] ? this.uploaderSubmit[2] : '',

        dangerGrade: this.problemGradeValue,
        dangerSource: this.problemSourceValue,
        dangerKind: this.problemSortValue,
        governKind: this.solveSortValue,
        changeResponerId: this.solveRespondentValue,
        governTime: this.solveTime,

        checkId: this.checkPersonValue,
        checkTime: this.startTime,

        changeStatus: '1',
        registrantId: JSON.parse(sessionStorage.getItem('loginInfo')).userId,
      })
      // console.log(res)
      if (res.code === 0) {
        this.$router.push('/problemResult')
      }
    },
    onConfirm(value) {
      this.problemGrade = value.text
      this.problemGradeValue = value.value
      this.showPicker = false
    },
    onConfirm1(value) {
      this.problemSource = value.text
      this.problemSourceValue = value.value
      this.showPicker1 = false
    },
    onConfirm2(value) {
      this.problemSort = value.text
      this.problemSortValue = value.value
      this.showPicker2 = false
    },
    onConfirm3(value) {
      this.solveSort = value.text
      this.solveSortValue = value.value
      this.showPicker3 = false
    },
    onConfirm4(value) {
      this.solveRespondent = value.text
      this.solveRespondentValue = value.value
      this.showPicker4 = false
    },
    onConfirm5(value) {
      this.checkPerson = value.text
      this.checkPersonValue = value.value
      this.showPicker5 = false
    },
    beforeRead(file) {
      console.log(file)
      if (
        file.type !== 'image/png' &&
        file.type !== 'image/jpeg' &&
        file.type !== 'image/jpg'
      ) {
        this.$toast.fail('请上传 png,jpg格式图片')
      }
      this.afterRead(file)
    },

    async afterRead(file) {
      // 此时可以自行将文件上传至服务器
      const formData = new FormData()
      const readFile = file.file || file
      // this.testMsg = readFile
      // this.testMsg=readFile
      formData.append('file', readFile)
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
      })
      const res = await uploadApi(formData)

      // this.testMsg = res
      if (res.code === 0) {
        this.$toast.success('上传成功')
        this.uploaderSubmit.push(res.data)
        this.uploader1.push({
          url: res.data,
        })
      } else {
        this.$toast.error('上传失败')

        this.uploader1.pop()
        // console.log(this.uploader1)
      }
      this.$toast.clear()
      setTimeout(() => {
        this.$toast.clear()
      }, 3000)
    },
    deleteSubmitPic(e, detail) {
      this.uploaderSubmit.splice(detail.index, 1)
      this.uploader1.splice(detail.index, 1)
    },
    confirmDate(e) {
      this.currentDate = this.formatDate(e)
      this.startTime = this.formatDate(e)
      this.cancelShowTimePicker()
    },
    formatDate(date) {
      // 获取年、月、日、时、分、秒
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0') // 获取小时
      const minutes = String(date.getMinutes()).padStart(2, '0') // 获取分钟
      const seconds = String(date.getSeconds()).padStart(2, '0') // 获取秒
      // 拼接成目标格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    cancelShowTimePicker() {
      this.showTimePicker = false
    },
 
  },
  mounted() {},
  watch: {},
  computed: {},
  filters: {},
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  background: #f7f7f7;
}
.formBox {
  padding: 16px;
  background: #f7f7f7;
  padding-bottom: 60px;
  .formTitle {
    font-weight: bold;
    font-size: 16px;
    color: #2f3133;
    margin-bottom: 16px;
  }
  .formItem {
    border-radius: 10px; /* 设置圆角大小 */
    overflow: hidden; /* 隐藏超出部分 */
    background-color: #fff; /* 可选：设置背景颜色 */
    margin-bottom: 12px;
    .inputCss {
      border: none;
      outline: none;
      background: transparent;
      font-size: 14px;
      text-align: right; /* 添加这行代码 */
    }
    .cellCss {
      box-sizing: border-box;
      width: 100%;
      padding: 10px 16px;
      overflow: hidden;
      color: #323233;
      font-size: 14px;
      line-height: 24px;
      background-color: #fff;
      .cellCssTitle {
        margin-bottom: 10px;
      }
      textarea {
        width: 100%;
        border: none;
      }
    }
  }
}

.van-cell {
  align-items: center;
  ::v-deep .van-field__label {
    color: #323233 !important ;
  }
}
.van-cell__value {
  overflow: visible;
}
</style>
